<template>
  <a-modal
    v-model:open="visible"
    title="编辑用户信息"
    :confirm-loading="loading"
    @ok="handleSubmit"
    @cancel="handleCancel"
    width="600px"
  >
    <a-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      layout="vertical"
    >
      <a-form-item label="用户名" name="userName">
        <a-input
          v-model:value="formData.userName"
          placeholder="请输入用户名"
          :maxlength="50"
        />
      </a-form-item>

      <a-form-item label="头像" name="userAvatar">
        <a-input
          v-model:value="formData.userAvatar"
          placeholder="请输入头像URL"
        />
        <div v-if="formData.userAvatar" class="avatar-preview">
          <a-avatar :src="formData.userAvatar" :size="64" />
        </div>
      </a-form-item>

      <a-form-item label="个人简介" name="userProfile">
        <a-textarea
          v-model:value="formData.userProfile"
          placeholder="请输入个人简介"
          :rows="4"
          :maxlength="200"
          show-count
        />
      </a-form-item>

      <a-form-item label="用户角色" name="userRole">
        <a-radio-group v-model:value="formData.userRole">
          <a-radio value="user">
            <a-tag color="blue">普通用户</a-tag>
          </a-radio>
          <a-radio value="admin">
            <a-tag color="green">管理员</a-tag>
          </a-radio>
        </a-radio-group>
        <div class="role-description">
          <a-alert
            v-if="formData.userRole === 'admin'"
            message="管理员权限说明"
            description="管理员可以访问用户管理、应用管理等后台功能，请谨慎设置。"
            type="warning"
            show-icon
          />
          <a-alert
            v-else
            message="普通用户权限说明"
            description="普通用户只能使用基本功能，无法访问管理后台。"
            type="info"
            show-icon
          />
        </div>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from 'vue'
import { message } from 'ant-design-vue'
import type { FormInstance } from 'ant-design-vue'
import { updateUser, getUserById } from '@/api/userController'

interface Props {
  open: boolean
  userId?: number
}

interface Emits {
  (e: 'update:open', value: boolean): void
  (e: 'success'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const formRef = ref<FormInstance>()
const loading = ref(false)
const visible = ref(false)

// 表单数据
const formData = reactive({
  id: 0,
  userName: '',
  userAvatar: '',
  userProfile: '',
  userRole: 'user'
})

// 表单验证规则
const rules = {
  userName: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 1, max: 50, message: '用户名长度在1-50个字符', trigger: 'blur' }
  ],
  userRole: [
    { required: true, message: '请选择用户角色', trigger: 'change' }
  ]
}

// 监听props变化
watch(
  () => props.open,
  async (newVal) => {
    visible.value = newVal
    if (newVal && props.userId) {
      await loadUserData()
    }
  },
  { immediate: true }
)

// 监听visible变化
watch(visible, (newVal) => {
  emit('update:open', newVal)
})

// 加载用户数据
const loadUserData = async () => {
  if (!props.userId) return

  try {
    loading.value = true
    const res = await getUserById({ id: props.userId })

    if (res.data.code === 0 && res.data.data) {
      const userData = res.data.data
      formData.id = userData.id || 0
      formData.userName = userData.userName || ''
      formData.userAvatar = userData.userAvatar || ''
      formData.userProfile = userData.userProfile || ''
      formData.userRole = userData.userRole || 'user'
    } else {
      message.error('加载用户数据失败：' + res.data.message)
    }
  } catch (error) {
    console.error('加载用户数据失败:', error)
    message.error('加载用户数据失败')
  } finally {
    loading.value = false
  }
}

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value?.validate()
    loading.value = true

    const updateData: API.UserUpdateRequest = {
      id: formData.id,
      userName: formData.userName,
      userAvatar: formData.userAvatar,
      userProfile: formData.userProfile,
      userRole: formData.userRole
    }

    const res = await updateUser(updateData)

    if (res.data.code === 0) {
      message.success('用户信息更新成功')
      visible.value = false
      emit('success')
    } else {
      message.error('更新失败：' + res.data.message)
    }
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    loading.value = false
  }
}

// 取消操作
const handleCancel = () => {
  visible.value = false
  formRef.value?.resetFields()
}
</script>

<style scoped>
.avatar-preview {
  margin-top: 8px;
}

.role-description {
  margin-top: 8px;
}
</style>
